'use client'

import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { ArrowLeft, Loader2, AlertCircle } from 'lucide-react'
import Link from 'next/link'
import { Sidebar } from '@/components/sidebar'
import { Alert, AlertDescription } from '@/components/ui/alert'

const SPECIALTY_NAMES: Record<string, string> = {
  piping: '配管专业',
  electrical: '电气专业', 
  hvac: '暖通专业',
  communication: '通信专业',
  instrumentation: '仪表专业'
}

interface Device {
  id: string;
  name: string;
  classificationCode: string;
  specialty: string;
  namingTableId?: string;
  positionTableId?: string;
  baseParamsTableId?: string;
  techSpecTableId?: string;
}

export default function SpecialtyDetailPage() {
  const params = useParams()
  const specialty = params.specialty as string
  
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [devices, setDevices] = useState<Device[]>([])

  useEffect(() => {
    async function loadSpecialtyData() {
      if (!specialty) return;
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/specialty/${specialty}`);
        const result = await response.json();

        if (!response.ok || !result.success) {
          throw new Error(result.error || `未能加载“${SPECIALTY_NAMES[specialty]}”的数据`);
        }
        
        setDevices(result.devices);
      } catch (err) {
        setError(err instanceof Error ? err.message : '加载数据时发生未知错误');
      } finally {
        setLoading(false);
      }
    }
    
    loadSpecialtyData();
  }, [specialty]);

  return (
    <div className="flex h-screen bg-gray-50">
      <Sidebar dataCounts={{}} />
      <div className="flex-1 flex flex-col overflow-hidden">
        <div className="bg-white border-b px-6 py-4">
          <Link href="/" className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 mb-4">
            <ArrowLeft className="h-4 w-4 mr-1" />
            返回数据中台
          </Link>
          <h1 className="text-2xl font-bold text-gray-900">
            {SPECIALTY_NAMES[specialty] || '专业详情'}
          </h1>
        </div>

        <div className="flex-1 overflow-auto p-6">
          <Card>
            <CardHeader>
              <CardTitle>设备列表</CardTitle>
              <CardDescription>
                以下是属于“{SPECIALTY_NAMES[specialty]}”的所有设备。
              </CardDescription>
            </CardHeader>
            <CardContent>
              {loading && (
                <div className="text-center py-8">
                  <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2" />
                  <p>正在加载设备...</p>
                </div>
              )}
              {error && (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}
              {!loading && !error && (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>设备名称</TableHead>
                      <TableHead>分类码</TableHead>
                      <TableHead>对象命名</TableHead>
                      <TableHead>基础参数</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {devices.length > 0 ? (
                      devices.map((device) => (
                        <TableRow key={device.id}>
                          <TableCell>{device.name}</TableCell>
                          <TableCell>{device.classificationCode}</TableCell>
                          <TableCell>{device.namingTableId || 'N/A'}</TableCell>
                          <TableCell>{device.baseParamsTableId || 'N/A'}</TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell colSpan={4} className="text-center">
                          该专业下没有找到任何设备。
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}